package com.example.textprovider0216;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.provider.ContactsContract;
import android.provider.Telephony;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.tbruyelle.rxpermissions3.RxPermissions;

import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;

import io.reactivex.rxjava3.functions.Consumer;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final int REQ_CODE = 1;
    private static final int REA_CODE = 0XF1;
    private ImageView imageView;

    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.btn_1);
        imageView=findViewById(R.id.aaa);

        getRemoteUsers();//点击事件
        rxpermissions();//为系统获取权限

    }

    /**
     * 点击的时候去获取
     */
    private void getRemoteUsers() {//点击事件
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //HuoQudata();//获取其他app数据库数据contentprovider0216
                //selectdata();//根据条件查询其他app数据库contentprovider0216
                //lll();//获取短信
                //persion();//获取联系人
                //selectphone();//根据条件查询手机联系人
                //addContacts();//添加联系人
                //deleteContactPhoneNumber();//根据条件删除联系人
                //inter();//手动创建文件
                //init();//选择图片回传至app
            }
        });
    }

    private void rxpermissions() {//获取权限
        new RxPermissions(this).request(Manifest.permission.READ_SMS,
                Manifest.permission.READ_CONTACTS,
                Manifest.permission.WRITE_CONTACTS)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Throwable {
                        if (aBoolean) {
                        }
                    }
                });
    }

    private void lll() {//获取短信
        ContentResolver resolver = getContentResolver();
        Cursor cursor = resolver.query(Telephony.Sms.CONTENT_URI, new String[]
                {Telephony.Sms.ADDRESS, Telephony.Sms.DATE, Telephony.Sms.TYPE,
                        Telephony.Sms.BODY}, null, null, null);
        cursor.moveToFirst();
        do {
            String values = cursor.getString(cursor.getColumnIndex(Telephony.Sms.ADDRESS));
            Log.d(TAG, "values" + values);
        } while (cursor.moveToNext());

    }

    private void persion() {//获取联系人
        ContentResolver resolver = getContentResolver();
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        Cursor cursor = resolver.query(uri, null, null, null, null);
        cursor.moveToFirst();
        do {
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            Log.d(TAG, "name" + name);
        } while (cursor.moveToNext());
    }

    private void HuoQudata() {//获取其他app数据库数据
        ContentResolver contentResolver = getContentResolver();
        Uri uri = Uri.parse("content://com.example.contentprovider0216");
        Cursor cursor = contentResolver.query(uri, null, null, null,
                null);
        String[] columnNames = cursor.getColumnNames();
        for (String columnName : columnNames) {
            Log.d(TAG, "columnName-------" + columnName);
        }
        while (cursor.moveToNext()) {
            Log.d(TAG, "-----------------------");
            for (String columnName : columnNames) {
                String value = cursor.getString(cursor.getColumnIndex(columnName));
                Log.d(TAG, columnName + "-----" + value);
            }
            Log.d(TAG, "-----------------------");
        }
        cursor.close();
    }

    private void selectdata() {//根据条件查询其他app数据库
        ContentResolver contentResolver = getContentResolver();
        Uri uri = Uri.parse("content://com.example.contentprovider0216");
        /**
         * 根据条件查询其他app数据库
         * 条件1：uri
         * 条件2；null
         * 条件3；根据什么条件来查询，通常输入数据库列名userName=?
         * 条件4；输入数据库列名对应的行的值
         */
        Cursor cursor = contentResolver.query(uri, null, "userName=?",
                new String[]{"lele"}, null);
        String[] columnNames = cursor.getColumnNames();
        for (String columnName : columnNames) {
            Log.d(TAG, "columnName-------" + columnName);
        }
        while (cursor.moveToNext()) {
            Log.d(TAG, "-----------------------");
            for (String columnName : columnNames) {
                String value = cursor.getString(cursor.getColumnIndex(columnName));
                Log.d(TAG, columnName + "-----" + value);
            }
            Log.d(TAG, "-----------------------");
        }
        cursor.close();
    }

    private void selectphone() {//根据条件查询手机联系人
        ContentResolver resolver = getContentResolver();
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        /**
         * 根据条件查询手机联系人
         * 条件1：uri
         * 条件2；null
         * 条件3；根据什么条件来查询，通常输入数据库列名userName=?
         * 条件4；输入数据库列名对应的行的值
         */
        String name = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + "=?";
        String[] va = new String[]{"小羊"};
        Cursor cursor = resolver.query(uri, null, name, va, null);
        cursor.moveToFirst();
        do {
            String value = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            Log.d(TAG, "name=====" + value);
            String phone = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            Log.d(TAG, "phone=====" + phone);
        } while (cursor.moveToNext());
        cursor.close();
    }

    public void addContacts() {
        Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
        Uri dataUri = Uri.parse("content://com.android.contacts/data");
        // 1. 在raw_contacts表中添加一个记录

        // 取raw_contacts表中contact_id的值
        Cursor cursor = getContentResolver().query(uri, new String[]{"contact_id"}, null, null, "contact_id desc limit 1");
        if (cursor != null && cursor.moveToFirst()) {
            int contact_id = cursor.getInt(0);
            contact_id++;
            cursor.close();

            ContentValues values = new ContentValues();
            values.put("contact_id", contact_id);
            getContentResolver().insert(uri, values);

            // 2. 根据上面添加记录的id, 取data表中添加三条数据

            // 存号码
            values = new ContentValues();
            values.put("mimetype", "vnd.android.cursor.item/phone_v2");
            values.put("data1", "10086");
            values.put("raw_contact_id", contact_id);
            getContentResolver().insert(dataUri, values);

            // 存姓名
            values = new ContentValues();
            values.put("mimetype", "vnd.android.cursor.item/name");
            values.put("data1", "中国移动");
            values.put("raw_contact_id", contact_id);
            getContentResolver().insert(dataUri, values);

            // 存邮箱
            values = new ContentValues();
            values.put("mimetype", "vnd.android.cursor.item/email_v2");
            values.put("data1", "10086@kengni.com");
            values.put("raw_contact_id", contact_id);
            getContentResolver().insert(dataUri, values);
        }
    }

    private void deleteContactPhoneNumber() {
        String contactName = "彩虹";
        //根据姓名求id
        Uri uri = ContactsContract.RawContacts.CONTENT_URI;
        ContentResolver resolver = getContentResolver();
        String where = ContactsContract.PhoneLookup.DISPLAY_NAME;
        Cursor cursor = resolver.query(uri, new String[]{ContactsContract.Data._ID}, where + "=?", new String[]{contactName}, null);
        if (cursor.moveToFirst()) {
            int id = cursor.getInt(0);
            //根据id删除data中的相应数据
            resolver.delete(uri, where + "=?", new String[]{contactName});
            uri = ContactsContract.Data.CONTENT_URI;
            resolver.delete(uri, ContactsContract.Data.RAW_CONTACT_ID + "=?", new String[]{id + ""});
        }
        Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
    }

    private void inter() {//手动创建文件
        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
        //指定文件类型为文本文件
        intent.setType("text/plain");
        //设置文件名
        intent.putExtra(Intent.EXTRA_TITLE, "create_file.text");

        startActivityForResult(intent, REQ_CODE);
    }

    private void init() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.setType("image/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, REA_CODE);
    }

    /**
     * 接收ActivityForResult所传回来的值
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode,  Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK){
            switch (requestCode){
                case REA_CODE:
                    try {
                        imageView.setImageBitmap(BitmapFactory.decodeFileDescriptor(getContentResolver().openFileDescriptor(data.getData(),"r").getFileDescriptor()));
                        getContentResolver().openFileDescriptor(data.getData(),"r").close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }
        }
    }


}


